/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imsx.converter;

/**
 *
 * @author mivkys
 */

import com.imsx.controller.util.Driver;
import com.imsx.model.Producto;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

@ManagedBean
public class ProductoConverter implements Converter {
    private Map<String, Producto> ejbFacade = new HashMap<>();
    
    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        try {
            Driver.findProducto(new Mongo().getDB("amazondb"), null, ejbFacade);
            if (value == null || value.length() == 0 ) {
                return null;
            }
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(ProductoConverter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MongoException ex) {
            Logger.getLogger(ProductoConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return this.ejbFacade.get(getKey(value));
    }

    java.lang.String getKey(String value) {
        return value;
    }

    String getStringKey(java.lang.String value) {
        return value;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null
                || (object instanceof String && ((String) object).length() == 0)) {
            return null;
        }
        if (object instanceof Producto) {
            Producto o = (Producto) object;
            return getStringKey(o.getProductoId());
        } else {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Producto.class.getName()});
            return null;
        }
    }

}

